<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <style>
      .container {
        display: flex;
        flex-direction: column;
      }
      .container img {
        width: 500px;
        height: 300px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <img src="./imgs/loading.gif" data-img="./imgs/dog.gif" />
      <img src="./imgs/loading.gif" data-img="./imgs/dog.gif" /><img
        src="./imgs/loading.gif"
        data-img="./imgs/dog.gif"
      /><img src="./imgs/loading.gif" data-img="./imgs/dog.gif" /><img
        src="./imgs/loading.gif"
        data-img="./imgs/dog.gif"
      /><img src="./imgs/loading.gif" data-img="./imgs/dog.gif" /><img
        src="./imgs/loading.gif"
        data-img="./imgs/dog.gif"
      /><img src="./imgs/loading.gif" data-img="./imgs/dog.gif" /><img
        src="./imgs/loading.gif"
        data-img="./imgs/dog.gif"
      /><img src="./imgs/loading.gif" data-img="./imgs/dog.gif" /><img
        src="./imgs/loading.gif"
        data-img="./imgs/dog.gif"
      />
      <script>
        //懒加载  lazy-load  加载资源不是一次性所有都加载 按需求加载资源
        //懒加载图片

        function loadImg() {
          //判断图片是否需要加载 如果需要加载 那么把data-img设置成scr
          var imgs = document.querySelectorAll("img");
          imgs.forEach(function (img) {
            var num = img.getBoundingClientRect().bottom;
            if (num < window.innerHeight) {
              //加载图片
              img.src = img.getAttribute("data-img");
              //把data-img的值赋值给img.src
            }
          });
        }
        loadImg();

        //监听 滚动事件
        window.onscroll = function () {
          loadImg();
        };
      </script>
    </div>
  </body>
</html>
